//
//  CustomTagAttachment.swift
//  MarkdownUIKit
//
//  Created by nowcoder on 2025/1/5.
//

import Foundation

public class CustomTagAttachment: NSTextAttachment {
    public let tagInfo: ParsedTagInfo
    
    public init(tagInfo: ParsedTagInfo, bounds: CGRect) {
        self.tagInfo = tagInfo
        super.init(data: nil, ofType: nil)
        self.bounds = bounds
        let size: CGFloat = 20
        // 确保附件有足够的点击区域
        if bounds.size.width < size {
            self.bounds.size.width = size
        }
        if bounds.size.height < size {
            self.bounds.size.height = size
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 重写此方法以确保附件在文本中正确对齐
    override public func attachmentBounds(for textContainer: NSTextContainer?, proposedLineFragment lineFrag: CGRect, glyphPosition position: CGPoint, characterIndex charIndex: Int) -> CGRect {
        var rect = bounds
        rect.origin.y = -6 // 微调垂直位置以更好地对齐文本
        rect.origin.x = -4
        return rect
    }
}
